package chat

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"strconv"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func SChat(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	userId, _ := strconv.Atoi(c.Param("userId"))

	cli := &Client{
		Friendsid: int64(userId),
		Conn:      conn,
		Sender:    make(chan *message, 10),
	}
	Clients[int64(userId)] = cli

	go cli.ReadMessage()
	go cli.WriteMessage()
}

func LChat(c *gin.Context) {
	userId, _ := strconv.Atoi(c.Param("userId"))
	if client, ok := Clients[int64(userId)]; ok {
		client.Conn.Close()
	}
	delete(Clients, int64(userId))
}

